import 'package:flutter/material.dart';
import 'package:hi_flutter/app_page.dart';

class ScrollControllerDemoPage extends StatefulWidget {
  const ScrollControllerDemoPage({super.key});

  @override
  State<ScrollControllerDemoPage> createState() =>
      _ScrollControllerDemoPageState();
}

class _ScrollControllerDemoPageState extends State<ScrollControllerDemoPage> {
  final ScrollController _controller = ScrollController();

  bool showToTopBtn = false; //是否显示“返回到顶部”按钮

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller.addListener(() {
      print(_controller.offset); //打印滚动位置
      if (_controller.offset < 1000 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_controller.offset >= 1000 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AppPage(
        body: ListView.builder(
          controller: _controller,
          itemCount: 100,
          itemExtent: 50.0,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text("$index"),
            );
          },
        ),
        floatingActionButton: showToTopBtn
            ? FloatingActionButton(
                child: const Icon(Icons.arrow_upward),
                onPressed: () {
                  _controller.animateTo(0.0,
                      duration: const Duration(milliseconds: 200),
                      curve: Curves.ease);
                },
              )
            : null);
  }
}
